import db from './db'
import store from '../store/store'
import md5 from "./md5.js";
import config from './config'
var baseUrl = config.website;
// var baseUrl = 'http://snnew.wistechina.com/api';
var headers = {
	"content-type": "application/x-www-form-urlencoded",
	"api-name": "wxapp",

}
// store.commit('setToken', 2953)
store.commit('setToken', db.get('token', null) ? db.get('token') : '')
// 数据签名
function getSignature() {
	return md5.hex_md5("ec32286d0718118861afdbf6e401ee81")
}

function formatData(data) {
	const options = {
		data: data
	}
	if (JSON.stringify(options.data) !== '{}') { //将post请求参数变为字符串，json数组只处理一层  
		let res = []
		for (let key in options.data) {

			if ('object' == typeof(options.data[key])) {
				if (!(options.data[key] instanceof Array)) { //对象就直接转为字符串  
					res.push(encodeURIComponent(key) + '=' + encodeURIComponent(JSON.stringify(options.data[key])))
				} else { //数组处理  
					for (let i = 0; i < options.data[key].length; i++) { //  
						res.push(encodeURIComponent(key) + '[]=' + encodeURIComponent(options.data[key][i]))
					}
				}
			} else {
				res.push(encodeURIComponent(key) + '=' + encodeURIComponent(options.data[key]))
			}
		}
		return res.join("&")
		
		
	}
}
const request = {
	baseUrl: baseUrl,
	fileUrl: "https://imgs.wkdns.cn/flyman",
	checkCode(code, msg = "请求错误") {
		console.log(code)
		switch (code) {
			case 10306:
				uni.showToast({
					icon: "none",
					title: '请登录'
				})
				uni.reLaunch({
					url: '/pages/index/index'
				});
				break
			case 10307:
				uni.showToast({
					icon: "none",
					title: '登录超时，请重新登录'
				})
				uni.reLaunch({
					url: '/pages/index/index'
				});
				break
			case 8:
				uni.showToast({
					icon: "none",
					title: '登录超时，请重新登录'
				})
				uni.reLaunch({
					url: '/pages/index/index'
				});
				break
			case 201:
				store.commit('setToken', '')
				db.save('token', '')
				db.save('userInfo', {})
				uni.showToast({
					icon: "none",
					title: msg
				})
				uni.reLaunch({
					url: '/pages/index/index'
				});
				break
			case 202:
				// uni.showToast({
				// 	icon: "none",
				// 	title: '登录超时，请重新登录'
				// })
				uni.reLaunch({
					url: '/pages/index/service'
				});
				break
			case -101:
				uni.showToast({
					icon: "none",
					title: "请登录"
				})
				// uni.reLaunch({
				// 	url: '/pages/login/index'
				// });
				break
			case 401:
				uni.showToast({
					icon: "none",
					title: "请登录"
				})
				break
			default:
				uni.showToast({
					icon: "none",
					title: msg
				})
				break
		}
	},
	login(url, params) {
		if (store.state.token) {
			headers['api-token'] = store.state.token
		}
		params['signature'] = getSignature()
		return new Promise((resolve, reject) => {
			uni.request({
				url: baseUrl + url, //仅为示例，并非真实接口地址。
				method: "POST",
				header: headers,
				data: params,
				success: (res) => {

					if (res.statusCode != 200) {
						request.checkCode(res.statusCode, res.data.message)

						reject(res)
					} else {
						if (res.data.code != 1) {
							request.checkCode(res.data.code, res.data.info)
						} else {
							resolve(res.data);
						}
					}
				},
				fail(err) {
					console.log(err)
					request.checkCode(404)
				}
			});
		});
	},
	post(url, params = {}) {
		if (store.state.token) {
			headers['api-token'] = store.state.token
		}
		return new Promise((resolve, reject) => {
			uni.request({
				url: baseUrl + url, //仅为示例，并非真实接口地址。
				method: "POST",
				data: formatData(params),
				header: headers,
				success: (res) => {
					if (res.statusCode != 200) {
						if (!params.nomsg) {
							request.checkCode(res.statusCode, res.data.message)
						}
						reject(res)
					} else {
						if (res.data.code != 1) {
							if (!params.nomsg) {
								request.checkCode(res.data.code, res.data.info)
							}
							reject(res)
						} else {
							resolve(res.data);
						}
					}
				},
				fail(err) {
					if (!params.nomsg) {
						request.checkCode(404)
					}
				}
			});
		});
	},
	get(url, params) {
		if (store.state.token) {
			headers['api-token'] = store.state.token
		}
		params['signature'] = getSignature()
		return new Promise((resolve, reject) => {
			uni.request({
				url: baseUrl + url, //仅为示例，并非真实接口地址。
				method: "GET",
				data: params,
				header: headers,
				success: (res) => {
					if (res.statusCode != 200) {
						request.checkCode(res.statusCode, res.data.message)
					} else {
						if (res.data.code != 1) {
							request.checkCode(res.data.code, res.data.message)
						} else {
							resolve(res.data);
						}

					}

				},
				fail(err) {
					request.checkCode(404)
				}
			});
		});

	},
	put(url, params) {
		if (store.state.token) {
			headers['api-token'] = store.state.token
		}
		params['signature'] = getSignature()
		return new Promise((resolve, reject) => {
			uni.request({
				url: baseUrl + url, //仅为示例，并非真实接口地址。
				method: "PUT",
				data: params,
				header: headers,
				success: (res) => {
					if (res.statusCode != 200) {
						request.checkCode(statusCode, res.data.message)
						reject(res)
					} else {
						resolve(res.data);
					}
				},
				fail(err) {
					request.checkCode(404)
				}
			});
		});

	},
	uploadFile(url, tempFilePath) {
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url: baseUrl + url, //仅为示例，非真实的接口地址
				filePath: tempFilePath,
				name: 'file',
				header: {
					'x-access-appid': headers['x-access-appid'],
					'api-token': store.state.token
				},
				formData: {
					'signature': getSignature()
				},
				success: (res) => {

					if (res.statusCode != 200) {
						request.checkCode(res.statusCode, res.data.message)
					} else {
						let info = JSON.parse(res.data)
						if (info.code != 10000) {
							request.checkCode(info.code, info.msg)
						} else {
							resolve(JSON.parse(res.data));
						}
					}
				},
				fail(err) {
					request.checkCode(404)
				}
			});
		});
	}
}

export default request